package com.sctvcloud.bazhong.ui.utils;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.fragment.BaseGeneraFragment;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.beans.FocusColumn;
import com.sctvcloud.bazhong.beans.LiveItem;
import com.sctvcloud.bazhong.beans.Titles;
import com.sctvcloud.bazhong.http.AbsListNetCallback;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.ui.adapter.LiveHomeAdapter;
import com.sctvcloud.bazhong.ui.util.IListShowData;
import com.sctvcloud.bazhong.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuyu on 2017/8/18.
 * 直播资源获取辅助
 */

public class LiveListGetHelper {

    public static final int ERROR_NO_TODAY = 200001;
    public static final int ERROR_NO_YESTERDAY = 200002;
    public static final int ERROR_NO_GETTING = 20001;

    private FocusColumn living;//直播资源
    private FocusColumn retrospect;//直播回顾（回看）
    private int livingTotal;
    private int retrospectTotal;
    private int livingPage = -1;
    private int retrospectPage = -1;
    private boolean hasAddFirtTitle;
    private boolean hasAddSecTitle;
    private boolean isContinue;
    private boolean isGeting;

    private String livingStr;
    private String retrospectStr;

    private final String ownerName;

    public LiveListGetHelper(BaseActivity activity, String livingStr, String retrospectStr) {
        ownerName = activity + "";
        this.livingStr = livingStr;
        this.retrospectStr = retrospectStr;
    }

    public LiveListGetHelper(BaseGeneraFragment fragment, String livingStr, String retrospectStr) {
        ownerName = fragment + "";
        this.livingStr = livingStr;
        this.retrospectStr = retrospectStr;
    }

    /**
     * 开放给Fragment调用的直播、回顾的数据请求方法
     * @param size
     * @param reset
     * @param callback
     * @return
     */
    public int getLiveList(int size, boolean reset, AbsListNetCallback<IListShowData> callback) {
        int re = -1;
        if (isGeting) {
            if (callback != null) {
                callback.onError(null, "this is in gettting", ERROR_NO_GETTING);
                callback.onEnd();
            }
            return re;
        }
        isGeting = true;
        if (reset) {
            reset();
        }
        if (living == null || isLivingGetedAll()) {
            if (isLivingGetedAll()) {
                re = 0;
            } else {
                //直播数据加载完成，接着加载直播回顾数据
                getRetrospect(size, null, callback);
                re = 2;
            }
        } else {
            re = 1;
            JLog.e("will getliving");
            getLiving(size, null, callback);
        }
        return re;
    }

    /**
     * 调用接口  获取直播数据
     * @param size
     * @param lis
     * @param callback
     */
    private void getLiving(final int size, final List<IListShowData> lis, AbsListNetCallback<IListShowData> callback) {
        if (living == null) {
            if (callback != null) {
                if (lis != null) {
                    callback.onSuc(lis);
                }
                callback.onError(null, "no living date", ERROR_NO_TODAY);
                callback.onEnd();
                isGeting = false;
            }
            return;
        }
        NetUtils.getNetAdapter().getLiveListPage(ownerName, living.getChannelUrl(), livingPage + 1
                , new AbsListNetCallback<LiveItem>(ListTypeUtils.NewsItem(), callback, livingPage + 1) {
                    private ArrayList<IListShowData> list;

                    @Override
                    public void onSuc(List<LiveItem> newsItems) {
                        livingPage = calledIndex;
                        livingTotal = getPageResponse().getData().getPageAll();
                        int to = ListUtils.getTotalSize(lis, list, hasAddFirtTitle ? -1 : 0);
                        if (size > 0 && size > to) {
                            isContinue = true;
                            if (isLivingGetedAll()) {
                                //直播数据加载完成
                                //连续加载直播回顾数据？
                                if (lis != null) {
                                    lis.addAll(list);
                                    getRetrospect(size, lis, (AbsListNetCallback) obj);
                                } else {
                                    getRetrospect(size, list, (AbsListNetCallback) obj);
                                }
                            } else {
                                //直播数据未完，继续加载直播数据
                                if (lis != null) {
                                    lis.addAll(list);
                                    JLog.e("will getliving " + this);
                                    getLiving(size, lis, (AbsListNetCallback) obj);
                                } else {
                                    JLog.e("will getliving  " + this);
                                    getLiving(size, list, (AbsListNetCallback) obj);
                                }
                            }
                        } else {
                            if (lis != null) {
                                lis.addAll(list);
                                ((AbsListNetCallback) obj).onSuc(lis);
                            } else {
                                ((AbsListNetCallback) obj).onSuc(list);
                            }
                        }
                    }

                    @Override
                    public List<LiveItem> doInBackground(List<LiveItem> newsItems) {
                        list = new ArrayList<>();
                        JLog.e("called index is " + calledIndex + " hase add " + hasAddFirtTitle + "   " + this);
                        if (ListUtils.isListValued(newsItems)) {
                            if (calledIndex == 0 || !hasAddFirtTitle) {
                                Titles t = new Titles();
                                t.setTitle(livingStr);
                                t.setViewType(LiveHomeAdapter.VIEWTYPE_TITLE);
                                hasAddFirtTitle = true;
                                list.add(t);
                            }
                            for (int i = 0; i < newsItems.size(); i++) {
                                LiveItem li = newsItems.get(i);
                                if (li != null) {
                                    li.setViewType(LiveHomeAdapter.VIEWTYPE_LIVE);
                                    li.setLiving(true);
                                    list.add(li);
                                }
                            }
//                            list.addAll(newsItems);
                        }
                        return super.doInBackground(newsItems);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        if (lis != null) {
                            ((AbsListNetCallback) obj).onSuc(lis);
                        }
                        ((AbsListNetCallback) obj).onError(ex, errorMsg, netCode);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        JLog.e("in living end is continue=" + isContinue);
                        if (isContinue) {
                            isContinue = false;
                        } else {
                            isGeting = false;
                            ((AbsListNetCallback) obj).onEnd();
                        }
                    }
                });
    }

    /**
     * 获取直播页面的直播回顾数据
     * @param size
     * @param list
     * @param callback
     */
    private void getRetrospect(final int size, final List<IListShowData> list, AbsListNetCallback<IListShowData> callback) {
        if (retrospect == null) {
            if (callback != null) {
                if (list != null) {
                    callback.onSuc(list);
                }
                callback.onError(null, "no retrospect date", ERROR_NO_YESTERDAY);
                callback.onEnd();
                isGeting = false;
            }
            return;
        }
        NetUtils.getNetAdapter().getLiveListPage(ownerName, retrospect.getChannelUrl(), retrospectPage + 1
                , new AbsListNetCallback<LiveItem>(ListTypeUtils.NewsItem(), callback, retrospectPage + 1) {
                    private ArrayList<IListShowData> lis;

                    @Override
                    public void onSuc(List<LiveItem> newsItems) {
                        retrospectPage = calledIndex;
                        retrospectTotal = getPageResponse().getData().getPageAll();
                        int to = ListUtils.getTotalSize(lis, list, calledIndex == 0 ? -2 : -1);
                        if (!isRetrospectDayGetedAll() && size > 0 && size > to) {
                            isContinue = true;
                            if (list != null) {
                                list.addAll(lis);
                                getRetrospect(size, list, (AbsListNetCallback) obj);
                            } else {
                                getRetrospect(size, lis, (AbsListNetCallback) obj);
                            }
                        } else {
                            if (lis != null) {
                                list.addAll(lis);
                                ((AbsListNetCallback) obj).onSuc(list);
                            } else {
                                ((AbsListNetCallback) obj).onSuc(lis);
                            }
                        }
                    }

                    @Override
                    public List<LiveItem> doInBackground(List<LiveItem> newsItems) {
                        lis = new ArrayList<>();
                        if (ListUtils.isListValued(newsItems)) {
                            if (calledIndex == 0) {
                                Titles t = new Titles();
                                t.setTitle(retrospectStr);
                                t.setViewType(LiveHomeAdapter.VIEWTYPE_TITLE);
                                hasAddFirtTitle = true;
                                lis.add(t);
                            }
                            for (int i = 0; i < newsItems.size(); i++) {
                                LiveItem li = newsItems.get(i);
                                if (li != null) {
                                    li.setViewType(LiveHomeAdapter.VIEWTYPE_LIVE);
                                    lis.add(li);
                                }
                            }
//                            lis.addAll(newsItems);
                        }
                        return super.doInBackground(newsItems);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        if (list != null) {
                            ((AbsListNetCallback) obj).onSuc(list);
                        }
                        ((AbsListNetCallback) obj).onError(ex, errorMsg, netCode);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        JLog.e("in retrospect end is continue=" + isContinue);
                        if (isContinue) {
                            isContinue = false;
                        } else {
                            isGeting = false;
                            ((AbsListNetCallback) obj).onEnd();
                        }
                    }
                });
    }

    private boolean isLivingGetedAll() {
        return livingPage >= 0 && livingTotal <= livingPage + 1;
    }

    private boolean isRetrospectDayGetedAll() {
        return retrospectPage >= 0 && retrospectTotal <= retrospectPage + 1;
    }

    private void reset() {
        resetLiving();
        resetRetrospect();
        isContinue = false;
    }

    private void resetLiving() {
        JLog.e("resetLiving called");
        livingTotal = 0;
        livingPage = -1;
        hasAddFirtTitle = false;
    }

    private void resetRetrospect() {
        retrospectTotal = 0;
        retrospectPage = -1;
    }

    public void setLiving(FocusColumn living) {
        if (this.living != living) {
            resetLiving();
        }
        this.living = living;
    }

    public void setRetrospect(FocusColumn retrospect) {
        if (this.retrospect != retrospect) {
            resetRetrospect();
        }
        this.retrospect = retrospect;
    }

    public boolean hasGetAll() {
        return (living == null || isLivingGetedAll()) && (retrospect == null || isRetrospectDayGetedAll());
    }

    public boolean hasValuedDate() {
        return living != null || retrospect != null;
    }
}
